<template>
	<view class="bgbox po_rel" @click="state.thiscode=null,state.chatinputmoretype=false">
		<un-navbar :titleText="聊天记录"
			:bgImgtype="2">
		</un-navbar>

		<view id="scrollview" class="scrollview"
			:style="`background-image: url(${store.state.bg_photo[state.userinfo.targetId]||''})`">

			<!-- @scrolltoupper="loadMore2" -->

			<scroll-view :scroll-y="state.scrollstatus" :scroll-top="state.scrolltop"  @scrolltolower="loadMore" @scrolltoupper="loadMore2" :scroll-into-view="state.toView"
				upper-threshold="50" lower-threshold="50" class="wi_100 flex" style="transform: rotate(180deg);"
				:style="`height:${state.scrollviewheight }px`">

				<view v-for="(item,index) in state.infolist" style="transform: rotate(180deg);" class="pa_top10"
					:id="item.messageUId">
					<view class="flex justify_center f_s24 te_black9 pa10" v-if="shouldShowTime(index)">{{gettimes(item.sentTime)}}</view>
					<view class="pa20 flex ma_tb30">
						<view class="multipleclass" v-if="state.onmultip"></view>
						<image class="multipleclass2" v-if="state.onmultip"
							src="../../static/image/chat/chatduogous.png"></image>
						<view class="flex flex1"
							:class="store.state.myinfo.system_code==item.senderUserId?'justify_end':''">

							<image v-if="item.direction==1"
								:src="(store.state.friendinfo[item.targetId]?.avatar || 'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png' )+'?x-oss-process=image/resize,p_30'"
								class="userimgs ma_right14"></image>


							<view @longpress="longpress($event,item)" :style="`z-index:${index};`" class="po_rel">
								<!-- 个人名片消息 -->
								<!-- @click="gouserinfo(item)" -->
								<view v-if="item.messageType==1&&item.identifier=='chat_diy'" class="ov_hidden"
									:class="item.direction==1?'grmpclass1':'grmpclass2'" >
									<view class="pa24 colorf9 te_black9 ">
										个人名片
									</view>
									<view class="pa24 bg_white flex align_center">
										<image :src="(item.fields.img||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'"
											class="userimgs ma_right14"></image>
										<view>
											{{item.fields.name}}
										</view>
									</view>
								</view>

								<!-- 普通文本消息 -->
								<view v-if="item.messageType==2"
									:class="item.direction==0?'dialoguecontent2 te_white':'dialoguecontent te_black'"
									class=" f_s32 break_all pa_tb24 pa_left24 pa_right20">{{item.text}}</view>

								<!-- 图片消息 -->
								<image v-if="item.messageType==4"
									:src="'data:image/png;base64,'+item.thumbnailBase64String" class=" bo_radius10"
									style="max-width: 300upx; max-height: 300upx;" mode="heightFix"
									@click="openimgs(item)"></image>
								<view v-show="state.thiscode== item.sentTime+item.messageUId"
									:class="item.direction==1?'operateclass2':'operateclass1'" class=" po_abs flex">
									<view :class="item.direction==1?'addboxssj1':'addboxssj2'"></view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										v-if="item.messageType==2"
										@click.stop="oncopy(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatfz.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white mt nowraps">复制</view>
									</view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										v-if="item.messageType==2||item.messageType==4"
										@click.stop="oncollect(item,item.direction),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatsc.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">收藏</view>
									</view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										@click.stop="ondelete(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatshanc.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">删除</view>
									</view>
									<view class="flex flex_column align_center ma_top10 ma_lr20"
										@click.stop="onforward(item),state.chatinputmoretype=false,state.thiscode=null">
										<image src="../../static/image/chat/chatzf.png" class="operateclassimg">
										</image>
										<view class="f_s24 te_white nowraps">转发</view>
									</view>
								</view>
							</view>
							<image v-if="item.direction==0"
								:src="(store.state.myinfo?.avatar ||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'"
								class="userimgs ma_left14"></image>

						</view>

						<!-- <view class="flex" v-else :style="`opacity:${lastids!=index?1:0}`">
							<image
								src="https://img2.baidu.com/it/u=3702685885,4113095768&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
								class="userimgs"></image>
						
							<view
								class="dialoguecontent bg_white ma_left14 fs32 break_all pa_tb24 pa_left24 pa_right20">
								{{item.text}}
							</view>
						</view> -->
					</view>
				</view>
				

			</scroll-view>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { friend_is_friend } from "@/api/addressbook";


	import { showToast, getscrollviewheight, throttle, debounce } from '@/utils/utils'
	import { onLoad, onShow, onUnload, onReady } from '@dcloudio/uni-app'
	import { ref, reactive, getCurrentInstance, watch, nextTick, computed } from 'vue'
	import { friend_info } from '@/api/addressbook'
	import { myadd_favourite } from '@/api/chat'



	import { useStore } from 'vuex'

	const store = useStore()
	const instance = getCurrentInstance(); // 获取组件实例
	onReady(async () => {
		state.scrollviewheight = await getscrollviewheight('#scrollview', instance)
	})

	const openimgs = (e) => {
		console.log(e)
		uni.previewImage({
			urls: [e.remote],
			longPressActions: {
				itemList: ['保存图片'],
				success: function (data) {
					uni.downloadFile({
						url: e, //仅为示例，并非真实的资源
						success: (res) => {
							if (res.statusCode === 200) {
								console.log(res);
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function () {
										uni.showToast({
											title: '保存成功',
											icon: 'success',
											duration: 2000
										});
									}
								});
							}
						}
					});


				},
				fail: function (err) {
					console.log(err.errMsg);
				}
			}
		});
	}

	const gettimes = (timestamp) => {
	
	
		const targetDate = new Date(timestamp);
		const now = new Date();
		const yesterday = new Date(now);
		yesterday.setDate(now.getDate() - 1);
	
		// 获取目标时间的年月日时分
		const targetYear = targetDate.getFullYear();
		const targetMonth = targetDate.getMonth() + 1;
		const targetDay = targetDate.getDate();
		const targetHour = targetDate.getHours();
		const targetMinute = targetDate.getMinutes();
	
		// 格式化时分
		const formattedTime = `${targetHour < 10 ? '0' : ''}${targetHour}:${targetMinute < 10 ? '0' : ''}${targetMinute}`;
	
		// 判断是否是今天
		if (
			targetYear === now.getFullYear() &&
			targetMonth === now.getMonth() + 1 &&
			targetDay === now.getDate()
		) {
			return '今天' + formattedTime;
		}
	
		// 判断是否是昨天
		if (
			targetYear === yesterday.getFullYear() &&
			targetMonth === yesterday.getMonth() + 1 &&
			targetDay === yesterday.getDate()
		) {
			return '昨天' + formattedTime;
		}
	
		// 判断是否是一周内
		const oneWeekAgo = new Date(now);
		oneWeekAgo.setDate(now.getDate() - 7);
		if (targetDate > oneWeekAgo) {
			const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
			const dayOfWeek = daysOfWeek[targetDate.getDay()];
			return `${dayOfWeek} ${formattedTime}`;
		}
	
		// 都不是，显示年月日
		return `${targetYear}-${targetMonth < 10 ? '0' : ''}${targetMonth}-${targetDay < 10 ? '0' : ''}${targetDay}`;
	
	}




	const gouserinfo = (item) => {

		friend_is_friend({
			system_code: item.fields.system_code
		}).then((res) => {
			if (res.data.is_friend) {
				uni.navigateTo({
					url: '/subPackages/addressbook/userinfo/index?type=1&portaltype=3&system_code=' + item.fields.system_code
				})
			} else {
				uni.navigateTo({
					url: '/subPackages/addressbook/userinfo/index?unique_code=' + item.fields.system_code
				})
			}
		}).catch((err) => {
			uni.showToast({
				title: err,
				icon: 'none'
			})
		})

	}





	const oncollect = (item, type) => {
		let data = {
			title: '来自于-' + (type == 1 ? state.userinfo.remark_name : '自己'),
			content: item.messageType == 2 ? item.text : item.remote,
			source_id: item.messageUId,
			favourite_type: item.messageType == 2 ? 'text' : item.messageType == 4 ? 'picture' : ''
		}

		console.log(data)
		myadd_favourite(data).then(res => {
			state.thiscode = null
			uni.showToast({
				title: '收藏成功',
				icon: 'success',
				duration: 2000
			});
		})
	}

	const onmultipfun = () => {
		state.onmultip = true
	}

	const onforward = (item) => {
		uni.setStorageSync('forward', [item])
		if (item.messageType == 4) {

			uni.getImageInfo({
				src: item.remote,
				success: function (image) {
					let datas = uni.getStorageSync('forward')
					datas[0].localurl = image.path
					uni.setStorageSync('forward', datas)
					console.log('datasdatas', datas)
					uni.navigateTo({
						url: '/pages/chat/forward'
					})
				}, fail: function (err) {
					uni.setStorageSync('forward', null)
					uni.showToast({
						title: '图片已过期或损坏',
						icon: 'none',
						duration: 2000
					});
				}
			});


			//let datas = uni.getStorageSync('forward')
		} else if (item.messageType == 2||item.messageType == 1) {
			uni.navigateTo({
				url: '/pages/chat/forward'
			})
		}


	}
	//sentTime
	const longpress = (e, item) => {
		console.log('eeeeeeeeeeeeeeee', e)
		console.log('itemitemitemitemitem', item)
		state.thiscode = item.sentTime + item.messageUId
	}
	// setInterval(()=>{
	// 	console.log('222222222222222222222',store.state.friendinfo)
	// },2000)

	const goset = (e) => {
		if (e == 1) {
			if (!state.userinfo.phone_number) {
				uni.showToast({
					title: '好友不存在，请先添加好友！',
					icon: 'none',
					duration: 2000
				});
				return
			}
			uni.navigateTo({
				url: '/pages/chat/set?targetId=' + state.userinfo.targetId
			})
		} else if (e == 2) {
			uni.navigateTo({
				url: '/subPackages/addressbook/userinfo/index?portaltype=1&type=1&system_code=' + state.userinfo.targetId
			})
		}

	}
	const oncopy = (item) => {
		state.thiscode = null
		uni.setClipboardData({
			data: item.text,
			success: function () {
				uni.showToast({
					title: '复制成功',
					icon: 'success',
					duration: 2000
				});
			}
		});
	}

	// let setdata=(newValue)=>{
	// 	scrollLeftTop.value = null
	// 	let obj = newValue;
	// 	let keys = Object.keys(obj);
	// 	let lastKey = keys[keys.length - 1];
	// 	lastids.value = lastKey

	// 	// nextTick(() => {
	// 	// 	setTimeout(() => {
	// 	// 		scrollLeftTop.value = 'lastid'
	// 	// 		setTimeout(() => {
	// 	// 			lastids.value = null
	// 	// 		}, 150)

	// 	// 	}, 200)
	// 	// })

	// }

	// watch(() => store.state.getMessages, (newValue, oldValue) => {
	// 	if (newValue) {
	// 		throttle(setdata(newValue), 2000)
	// 	}
	// }, {
	// 	deep: true, immediate: true
	// });


	onUnload(() => {
		store.commit('settargetId', null)//清空会话id
		store.commit('cleargetMessages')
		store.commit('setnolist', false)

	})

	const scrollLeftTop = ref<any>(null)

	let callback = {
		onMessageSaved: (res) => {
			console.log('onMessageSavedonMessageSaved', res)
			//...
		},
		onMessageSent: (res) => {
			console.log('onMessageSentonMessageSent', res)
			if (res.code == 0) {
				//store.dispatch('getMessages', state.userinfo.targetId,0)
				let datas = {
					num: 0,
					targetId: null,
					type: 1,
					targetId: state.userinfo.targetId,

				}

				store.dispatch('getConversations', datas)

			}

			//...
		}

	};


	const navigationinfo = ref<any>(uni.getStorageSync('navigationinfo'))



	const getlist = () => {
		let datas = {
			targetId: state.userinfo.targetId,
			times: state.infolist[state.infolist.length - 1].sentTime,
			type: 0
		}
		console.log('上拉数据2', datas)
		getinfo(datas)
	}

	const getlist2 = (e) => {
		let datass = {
			targetId: state.userinfo.targetId,
			times: state.infolist[0].sentTime,
			type: 1,
			num: 2,
			status:1
			
		}
		getinfo(datass)
		
		
		//const { scrollTop, scrollHeight, clientHeight } = e.mp?.detail || e.detail;
		// 判断是否滚动到底部
		// if (scrollTop<150&&!state.init) { // 留出10px的余地避免重复触发
		// 	state.scrollstatus=false
		// 	let datas = {
		// 		targetId: state.userinfo.targetId,
		// 		times: state.infolist[0].sentTime,
		// 		type: 1,
		// 		num: 1
		// 	}
		// 	getinfo(datas)
		// 	setTimeout(()=>{
		// 		let datass = {
		// 			targetId: state.userinfo.targetId,
		// 			times: state.infolist[0].sentTime,
		// 			type: 1,
		// 			num: 1
		// 		}
		// 		getinfo(datass)
		// 	},500)
		// }else{
		// 	console.log('没成功没成功没成功没成功没成功没成功没成功没成功没成功没成功没成功没成功没成功')
		// }

		
	}


	const loadMore = throttle(getlist, 100)
	const loadMore2 = throttle(getlist2, 0)


	const getinfo = async (info) => {

		console.log('infoinfo', info)
		let callback = {
			onSuccess: (res) => {
				console.log('获取到的消息是',res)
				if (info.type == 0) {
					console.log('上面的数据')
					res.t.map(item => {
						state.infolist.push(item)
					})
				} else {
					console.log('下面的数据')
					res.t.map(item => {
						state.infolist.unshift(item)
						state.scrolltop= 0
						setTimeout(()=>{
							state.scrolltop= 1
						},200)
						// if(info.status==1){
						// 	console.log('进来了')
						// 	state.scrolltop= 0
						// 	setTimeout(()=>{
						// 		state.scrolltop= 1
						// 	},200)
						// }
					})
					
				}
				
				

				//...
			},
			onError: (res) => {
				//...
			}
		};
		let code = await store.state.engine.getMessages(1, info.targetId, null, info.times, info.type, 2, info.num || 15, callback);
	}

	
	const ondelete = (item)=>{
		
		uni.showModal({
			title: '提示',
			content: '确认删除此条消息？',
			success: function (res) {
				if (res.confirm) {
					console.log(item)
					deletas()
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		
		let deletas = async()=>{
			console.log(item)
			let callback = {
			onMessagesDeleted:(res) => {
				store.commit('deletegetMessages',{
					messageUId:item.messageUId
				})
				
				
				let index = state.infolist.findIndex(items => items.messageUId === item.messageUId);
				 
				if (index !== -1) {
				    // 使用splice删除元素
				    state.infolist.splice(index, 1);
				}
				
				
				
				uni.showToast({
					title: '删除成功',
					icon: 'success',
					duration: 2000
				});
			//...
			}};
			let code = await store.state.engine.deleteMessages(1, state.userinfo.targetId, null,[item], callback);
		}
		
		
	}	
	
	
	const oninit = (targetId) => {
		state.userinfo.targetId = targetId





		let datas = {
			targetId: state.userinfo.targetId,
			times: state.time + 1,
			type: 0
		}

		let datas2 = {
			targetId: state.userinfo.targetId,
			times: state.time,
			type: 1,
			num:1
		}
		console.log('datas', datas)
		console.log('datas2', datas2)

		getinfo(datas)
		
		
		setTimeout(() => {
			state.toView = state.messageUId
			getinfo(datas2)
			setTimeout(()=>{
				state.init=false
			},100)
		}, 200)
		
		
		// setTimeout(() => {
		// 	getinfo(datas2)
		// 	setTimeout(() => {
		// 		state.toView = state.messageUId
		// 		setTimeout(()=>{
		// 			state.init=false
		// 		},100)
		// 	}, 500)
		// }, 100)
	
		friend_info({
			unique_code: state.userinfo.targetId
		}).then(res => {
			state.userinfo = res.data
			state.userinfo.phone_number == null
			state.userinfo.targetId = targetId
			let friendinfo = uni.getStorageSync('friendinfo')
			friendinfo[state.userinfo.targetId].remark_name = res.data.remark_name
			friendinfo[state.userinfo.targetId].avatar = res.data.contact_user_avatar
			friendinfo[state.userinfo.targetId].system_code = res.data.system_code
			uni.setStorageSync('friendinfo', friendinfo)
			store.commit('setfriendinfo', friendinfo)
		}).catch(res => {

		})
	}

	onShow(() => {
		if (uni.getStorageSync('above_info')) {//从个人信息---聊天页面跳过来的
			store.commit('settargetId', null)//清空会话id
			store.commit('cleargetMessages')
			store.commit('setnolist', false)

			oninit(uni.getStorageSync('above_info').targetId)
			console.log('222222222222', uni.getStorageSync('above_info').targetId)

			uni.setStorageSync('above_info', '')
		}

		if (uni.getStorageSync('forwardtype')) {
			uni.setStorageSync('forwardtype', null)
			uni.showToast({
				title: '转发成功',
				icon: 'success',
				duration: 2000
			});
		}
	})

	onLoad((e) => {

		if (e.targetId) {
			state.targetId = e.targetId
			state.messageUId = e.messageUId
			state.time = Number(e.time)
			state.chattype = e.type
			oninit(e.targetId)
		}


	})

	const state = reactive({
		scrolltop:0,
		scrollstatus:true,
		init:true,
		toView: '',
		infolist: [],
		chattype: null,
		time: null,
		onmultip: false,
		chatinputmoretype: false,
		thiscode: null,
		scrollviewheight: 0,
		userinfo: {
			targetId: null,
			phone_number: null
		},
		content: '',
	})
</script>
<style>

</style>

<style scoped lang="scss">
	$ztcolor: #39C7C1;

	.zttecolor {
		color: $ztcolor;
	}

	.ztbgcolor {
		background-color: $ztcolor;
	}

	.colorf9 {
		background: #F9F9F9;
	}

	.bgbox {
		width: 100vw;
		height: 100vh;
		// overflow: hidden;

		//background: linear-gradient(180deg, #F0F4FE 0%, #FFFFFF 40%, #FFFFFF 100%);

	}

	.addsclass {
		width: 30upx;
		height: 7upx;
		top: 0;
		right: 24upx;
		bottom: 0;
		margin: auto 0;
	}



	.bottomfsbq {
		width: 52upx;
		height: 52upx;
	}

	.userimgs {
		width: 84upx;
		height: 84upx;
		border-radius: 30upx;
	}

	.dialoguecontent {
		max-width: 460upx;
		border-radius: 0 20upx 20upx 20upx;
		position: relative;
		background-color: #ffffff;
	}

	.dialoguecontent2 {
		max-width: 460upx;
		border-radius: 20upx 0 20upx 20upx;
		position: relative;
		background-color: #2DB8B2;
	}

	.operateclass1 {
		background: #2F3736;
		// width: 500upx;
		height: 90upx;
		right: 0;
		top: -110upx;
		border-radius: 20upx;
	}

	.operateclass2 {
		background: #2F3736;
		// width: 500upx;
		height: 90upx;
		left: 0;
		top: -110upx;
		border-radius: 20upx;
	}

	.operateclassimg {
		width: 38upx;
		height: 38upx;
		// margin-bottom: 6upx;
	}

	.addboxssj1 {
		position: absolute;
		bottom: -31upx;
		/* 我们只是在视觉上将另外三个边框隐藏掉了，盒子的大小仍然是边框宽度的2倍 */
		left: 30upx;
		width: 0;
		height: 0;
		border: 16upx solid transparent;
		border-top-color: #2F3736;
	}

	.addboxssj2 {
		position: absolute;
		bottom: -31upx;
		/* 我们只是在视觉上将另外三个边框隐藏掉了，盒子的大小仍然是边框宽度的2倍 */
		right: 30upx;
		width: 0;
		height: 0;
		border: 16upx solid transparent;
		border-top-color: #2F3736;
	}

	.chatinputimg {
		width: 120upx;
		height: 120upx;
	}

	.multipleclass {
		margin-top: 25upx;
		margin-right: 16upx;
		width: 30upx;
		height: 30upx;
		border-radius: 50%;
		border: 2upx solid #D0D0D0;
	}

	.multipleclass2 {
		margin-top: 25upx;
		margin-right: 16upx;
		width: 34upx;
		height: 34upx;
	}

	.grmpclass1 {
		width: 460upx;
		border-radius: 0 20upx 20upx 20upx;
	}

	.grmpclass2 {
		width: 460upx;
		border-radius: 20upx 0 20upx 20upx;
	}

	.scrollview {
		background-repeat: no-repeat;
		background-size: cover;
		background-position: center center;
	}
</style>